﻿using LuShanTea.Common;
using LuShanTea.DTO;
using LuShanTea.Service;
using LuShanTea.Service.Entities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Newtonsoft;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LuShanTea.Web.Common;
using System.Net;
using System.IO;
using LuShanTea.Front.Web.App_Start;
using LuShanTea.IService;

namespace LuShanTea.Test
{
    class Program
    {

        public static CartService cartService { get; set; } = new CartService();
        
        static void Main(string[] args)
        {
            #region 测试案例
            //using (LuShanTeaContext ctx = new LuShanTeaContext())
            //{
            #region Test
            //AdminUserAddUpdateDto admin = new AdminUserAddUpdateDto();
            //admin.Email = "1028139084@qq.com";
            //admin.Gender = true;
            //admin.ImgSrc = "http://img4.imgtn.bdimg.com/it/u=2603659354,39736236&fm=27&gp=0.jpg";
            //admin.Name = "黎明";
            //admin.NickName = "NoRain";
            //admin.PassWord = "lck@123";
            //admin.PhoneNum = "18357028943";
            //AdminUserService ser = new AdminUserService();
            //ser.AddNew(admin);

            //User user = new User
            //{
            //    Email = "dsaasdasd",
            //    Gender = false,
            //    HashPwd = "fasdfsd",
            //    ImgSrc = "fasdfsdfsd",
            //    Name = "mortal",
            //    NiceName = "mortal",
            //    PhoneNumber = "asdfsd",
            //    Salt = "fasdf"
            //};
            //ctx.Users.Add(user);

            //ctx.SaveChanges();

            //ctx.Carts.Add(new Cart { UserId = user.Id });

            //ctx.SaveChanges();
            //Console.WriteLine(cartService.GetCartIdByUserId(2)); 


            //GoodAttr goodAttr = new GoodAttr()
            //{
            //    ArtDesc = "asdfsdfa",
            //    Level = "1级",
            //    ProduceTime = DateTime.Now,
            //    ProNumber = Guid.NewGuid().ToString(),
            //    ValidTime = "2015"
            //};
            //ctx.GoodAttrs.Add(goodAttr); 
            #endregion


            //}
            #region 验证码
            /*
		    for (int i = 0; i < 10; i++)
            {
                //Console.WriteLine(CommonHelper.GetVertifyCode());
                //Thread.Sleep(1000);

                string res;
                Console.WriteLine(CommonHelper.CreateVerifyCode(out res));
                Console.WriteLine(res);
                Console.WriteLine("-----------");

                //Console.WriteLine(Guid.NewGuid().GetHashCode());
            }
              Console.WriteLine("ok");   */
            #endregion

            #region redis插入和查询数据
            //using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
            //{
            //    IDatabase db = redis.GetDatabase();//默认是访问 db0 数据库，可以通过方法参数指定数字访问不同的数据库
            //    // 设置键值对
            //    //db.StringSet("Name", "abc");
            //    // 获取
            //    string name= db.StringGet("Name");
            //    Console.WriteLine($"name={name}");
            //}

            #endregion

            // created,updated,deleted

            #region 未封装钱的插入数据
            Person p1 = new Person();
            p1.Id = 6;
            p1.Age = 8;
            p1.Name = "丑娘娘";
            //ElasticConnection client = new ElasticConnection("127.0.0.1", 9200);
            //var serializer = new JsonNetSerializer();
            ////第一个参数相当于“数据库”，第二个参数相当于“表”，第三个参数相当于“主键”
            //IndexCommand cmd = new IndexCommand("zsz", "persons", p1.Id.ToString());
            ////Put()第二个参数是要插入的数据
            //OperationResult result = client.Put(cmd, serializer.Serialize(p1));

            //string res = result.Result;
            //string[] ress = res.Split(',');
            //Console.WriteLine(ress.Count());
            //Console.WriteLine(ress[4]);
            ////var r = (Result)JsonConvert.DeserializeObject(ress[4]);
            //string[] ress2= ress[4].Split(':');
            //Console.WriteLine(ress2[1]);
            //string s = ress2[1].Trim('"');
            //if (s.Equals("updated")|| s.Equals("created"))
            //{
            //    if(s.Equals("updated"))
            //    {
            //        Console.WriteLine("创建成功了");
            //    }
            //    else
            //    {
            //        Console.WriteLine("更新成功");
            //    }

            //}
            //else
            //{
            //    Console.WriteLine("创建失败");
            //} 
            #endregion

            #region 未封装前的查询数据
            //ElasticConnection client = new ElasticConnection("127.0.0.1", 9200);
            //SearchCommand cmd = new SearchCommand("zsz", "persons");
            //var query = new QueryBuilder<Person>()
            //.Query(b =>
            // b.Bool(m =>
            ////并且关系
            //m.Must(t =>
            // //分词的最小单位或关系查询
            // t.QueryString(t1 => t1.DefaultField("Name").Query("丑娘娘"))
            // )
            // )
            //)
            //.Build();
            //var result = client.Post(cmd, query);
            //var serializer = new JsonNetSerializer();
            //var list = serializer.ToSearchResult<Person>(result);
            //foreach (var item in list.Documents)
            //{
            //    Console.WriteLine(item.Id+"-"+item.Name);
            //} 
            #endregion

            #region 插入数据
            /*
            GoodDTO dto = new GoodDTO();
            dto.CateGoriesId = 1;
            dto.CatoryName = "浆果";
            dto.CityId = 1;
            dto.CityName = "北京";
            dto.CreateDateTime = DateTime.Now;
            dto.Descible = "好吃";
            dto.Id = 8;
            bool result = LuShanTeaElasticSearch.Insert(dto);
            if (result)
            {
                Console.WriteLine("ok");
            }
            else
            {
                Console.WriteLine("error");
            } */
            #endregion

            #region 查询数据
            /*
             var query = new QueryBuilder<GoodDTO>()
                .Query(b =>
                 b.Bool(m =>
                //并且关系
                m.Must(t =>
                 //分词的最小单位或关系查询
                 //t.QueryString(t1 => t1.DefaultField("Descible").Query("好吃"))
                 t.QueryString(t1 => (t1.DefaultField("CityName").Query("北京")))
                 )
                 )
                )
                ;
             LuShanTeaElasticSearch.Search(query);*/
            #endregion

            #region 将所有的商品插入到elasticsearch中
            /*
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Good> bs = new BaseService<Good>(ctx);
                var goods =bs.GetAll();
                Console.WriteLine(goods.Count());
                foreach (var good in goods)
                {
                    GoodDTO dto = new GoodDTO();
                    dto.CateGoriesId = good.CateGoriesId;
                    dto.CityId = good.CityId;
                    dto.CreateDateTime = good.CreateDateTime;
                    dto.Descible = good.Describe;
                    dto.Id = good.Id;
                    dto.Name = good.Name;
                    dto.PackIds = good.Packs.Select(e=>e.Id).ToArray();
                    dto.PrePrice = good.Pre_Price;
                    dto.Price = good.Price;
                    dto.Selled = good.Selled;
                    
                    dto.TotalCount = good.TotalCount;
                    dto.Weight = good.Weight;
                    bool result = LuShanTeaElasticSearch.Insert(dto);
                    if (result)
                    {
                        Console.WriteLine($"ok:----id:{good.Id}-name:{good.Name}prePrice:{good.Pre_Price}-price:{good.Price}-selled:{good.Selled}-:weight:{good.Weight}");
                    }
                    else
                    {
                        Console.WriteLine("error");
                    }
                }
            }*/
            #endregion
            #endregion

            #region 注册
            //LuShanTeaSms sms = new LuShanTeaSms();
            //sms.Code = "asdf";
            //sms.PhoneNum = "16437815647";

            //AjaxResult res = sms.Send("url地址");
            //Console.WriteLine(res.Status);


            // //string str= Send("url地址", "userName=lck&appKey=xxx&templateId=1076&code=1101&phoneNum=18888888888");
            //                               // Console.WriteLine(str);

            //Console.ReadKey(); 
            #endregion

            LuShanEmailSms sms = new LuShanEmailSms();
            sms.Code = "1234";
            sms.Email = "1028139084@qq.com";
            sms.Send();
            Console.WriteLine("ok");
            Console.ReadKey();
            #region 从elasticsearch中获取所有的商品
            
            var query = new QueryBuilder<GoodDTO>()
                .Query(b =>
                 b.Bool(m =>
                //并且关系
                m.Must(t =>
                 //分词的最小单位或关系查询
                 t.QueryString(t1 => t1.DefaultField("Descible").Query("茶"))
                 //t.QueryString(t1 => (t1.DefaultField("CityName").Query("北京")))
                 )
                 )
                )
                ;
            var query2 = new QueryBuilder<GoodDTO>()
                .Query(b =>
                 b.Bool(m =>
                //并且关系
                m.Must(t =>
                 //分词的最小单位或关系查询
                 t.QueryString(t1 => t1.DefaultField("Name").Query("茶"))
                 //t.QueryString(t1 => (t1.DefaultField("CityName").Query("北京")))
                 )
                 )
                )
                ;
            var data= LuShanTeaElasticSearch.Search(query);
            var data2 = LuShanTeaElasticSearch.Search(query2);
            var data3=data.Concat(data2);
            foreach (var item in data3)
            {
                Console.WriteLine($"id={item.Id}---{item.Name}");
            }
            #endregion


            Console.ReadKey();
        }


        public static string Send(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
            writer.Write(postDataStr);
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码  
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();
            return retString;
        }
    }

    //[Serializable]
    class Person
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Result
    {
        public string result { get; set; }
    }
}
